#!/bin/bash

function install_pyenv {
    IS_CHANGED=$(cat ~/.bashrc | grep '# OneKeyMan install pyenv')
    if [ "$IS_CHANGED" != "" ]; then
        echo '已经安装了pyenv'
        return
    fi

    echo '检查 git 是否被安装'
    if ! [ -x "$(command -v git)" ]; then
	    echo '安装 git 工具'
        sudo apt install git
    fi

    echo '克隆 pyenv 仓库到本地'
    git clone https://github.91chi.fun/https://github.com/pyenv/pyenv.git ~/.pyenv \
	    && ls ~/.pyenv/plugins/python-build/share/python-build/pyston-2.* |xargs sed -i "s#DOWNLOAD='https://github.com/#DOWNLOAD='https://github.91chi.fun/github.com/#" 


    echo '添加环境变量'
    echo -e "\n# OneKeyMan install pyenv" >>~/.bashrc
    echo 'export PYENV_ROOT="$HOME/.pyenv"' >>~/.bashrc
    echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >>~/.bashrc
    echo 'eval "$(pyenv init -)"' >>~/.bashrc

    echo '替换为华为下载站'
    find ~/.pyenv/plugins/python-build/share/python-build -type f -maxdepth 1 | xargs sed -i 's/https:\/\/www.python.org\/ftp\/python/https:\/\/repo.huaweicloud.com\/python/g'

    echo '安装完毕！'
    echo 
    echo '用法提示：'                           
    echo -e "\t安装指定版本 pyenv install 3.10.7"
    echo -e "\t将版本配置为系统全局 pyenv global 3.10.7"
    echo -e "\t将版本配置为当前目录使用 pyenv local 3.10.7 会在当前目录创建 .python-version 文件"
    echo
    echo '激活方法（单选）：'
    echo -e "\t1. 请执行注销或重启让pyenv立即生效"
    echo -e "\t2. 在当前命令终端立即生效，执行 source ~/.bashrc"
    echo -e "\t3. 关闭命令终端，或（重）新启动终端"
}


install_pyenv